/**
 * Copyright 2018 人人开源 http://www.renren.io
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.ziyun.admin.web.modules.oss.controller;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.google.gson.Gson;
import io.renren.common.exception.RRException;
import io.renren.common.utils.*;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AliyunGroup;
import io.renren.common.validator.group.QcloudGroup;
import io.renren.common.validator.group.QiniuGroup;
import io.renren.modules.oss.cloud.CloudStorageConfig;
import io.renren.modules.oss.entity.SysOssEntity;
import io.renren.modules.oss.service.SysOssService;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * 文件上传
 * 
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017-03-25 12:13:26
 */
@RestController
@RequestMapping("sys/oss")
public class SysOssController {

	@Value("${oss.endpoint}")
	private String endpoint;

	@Value("${oss.bucketName}")
	private String bucketName;

	@Value("${oss.picLocation}")
	private String picLocation;

	@Value("${oss.accessKeyId}")
	private String accessKeyId;

	@Value("${oss.accessKeySecret}")
	private String accessKeySecret;

	@Value("${oss.host}")
	private String host;

	@Value("${oss.callbackUrl}")
	private String callbackUrl;

	@Autowired
	private SysOssService sysOssService;

    private final static String KEY = ConfigConstant.CLOUD_STORAGE_CONFIG_KEY;
	
	/**
	 * 列表
	 */
	@RequestMapping("/list")
	@RequiresPermissions("sys:oss:all")
	public R list(@RequestParam Map<String, Object> params){
		PageUtils page = sysOssService.queryPage(params);

		return R.ok().put("page", page);
	}


/*
    */
/**
     * 云存储配置信息
     *//*

    @RequestMapping("/config")
    @RequiresPermissions("sys:oss:all")
    public R config(){
        CloudStorageConfig config = sysConfigService.getConfigObject(KEY, CloudStorageConfig.class);

        return R.ok().put("config", config);
    }
*/


/*	*//**
	 * 保存云存储配置信息
	 *//*
	@RequestMapping("/saveConfig")
	@RequiresPermissions("sys:oss:all")
	public R saveConfig(@RequestBody CloudStorageConfig config){
		//校验类型
		ValidatorUtils.validateEntity(config);

		if(config.getType() == Constant.CloudService.QINIU.getValue()){
			//校验七牛数据
			ValidatorUtils.validateEntity(config, QiniuGroup.class);
		}else if(config.getType() == Constant.CloudService.ALIYUN.getValue()){
			//校验阿里云数据
			ValidatorUtils.validateEntity(config, AliyunGroup.class);
		}else if(config.getType() == Constant.CloudService.QCLOUD.getValue()){
			//校验腾讯云数据
			ValidatorUtils.validateEntity(config, QcloudGroup.class);
		}

        sysConfigService.updateValueByKey(KEY, new Gson().toJson(config));

		return R.ok();
	}*/
	
/*

	*/
/**
	 * 上传文件
	 *//*

	@RequestMapping("/upload")
	@RequiresPermissions("sys:oss:all")
	public R upload(@RequestParam("file") MultipartFile file) throws Exception {
		if (file.isEmpty()) {
			throw new RRException("上传文件不能为空");
		}

		//上传文件
		String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
		String url = OSSFactory.build().uploadSuffix(file.getBytes(), suffix);

		//保存文件信息
		SysOssEntity ossEntity = new SysOssEntity();
		ossEntity.setUrl(url);
		ossEntity.setCreateDate(new Date());
		sysOssService.insert(ossEntity);

		return R.ok().put("url", url);
	}
*/


	/**
	 * 删除
	 */
	@RequestMapping("/delete")
	@RequiresPermissions("sys:oss:all")
	public R delete(@RequestBody Long[] ids){
		sysOssService.removeByIds(Arrays.asList(ids));

		return R.ok();
	}


	/**
	 * 获取ｏｓｓ　验签
	 * @param request
	 * @param response
	 */
	@GetMapping("/getSignature")
	@ResponseBody
	public void getSignature (HttpServletRequest request, HttpServletResponse response){
		String dir = request.getParameter("dir");
		dir = picLocation+ dir;
		String ori_filename = request.getParameter("ori_filename");
		String fileType = null;
		if (StringUtils.isNotEmpty(ori_filename)){
			fileType =  ori_filename.substring(ori_filename.lastIndexOf("."));
		}

		String newFileName = System.currentTimeMillis()+ fileType;
		//dir += newFileName;

 		OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		try{
			long expireTime = 30;
			long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
			Date expiration = new Date(expireEndTime);
			PolicyConditions policyConds = new PolicyConditions();
			policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
			policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

			String postPolicy = client.generatePostPolicy(expiration, policyConds);
			byte[] binaryData = postPolicy.getBytes("utf-8");
			String encodedPolicy = BinaryUtil.toBase64String(binaryData);
			String postSignature = client.calculatePostSignature(postPolicy);

			Map<String, String> respMap = new LinkedHashMap<String, String>();
			respMap.put("accessid", accessKeyId);
			respMap.put("policy", encodedPolicy);
			respMap.put("signature", postSignature);
			//respMap.put("expire", formatISO8601Date(expiration));
			respMap.put("dir", dir);
			respMap.put("newFileName", newFileName);
			respMap.put("ori_filename", ori_filename);
			respMap.put("host", host);
			respMap.put("expire", String.valueOf(expireEndTime / 1000));
			respMap.put("callback_var", new JSONObject().toString());



			JSONObject callBackParams = new JSONObject();
			callBackParams.put("callbackUrl", callbackUrl);
			callBackParams.put("callbackBody", "oldFilename='"+ ori_filename +"'&date='"+ DateUtils.format(new Date(),DateUtils.DATE_TIME_PATTERN) +"'&filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}");
			callBackParams.put("callbackBodyType", "application/x-www-form-urlencoded");
			respMap.put("callback", BinaryUtil.toBase64String(callBackParams.toString().getBytes("utf-8")));


			JSONObject jaRS = JSONObject.fromObject(respMap);
			//返回值
			System.out.println(respMap);
			response.setHeader("Access-Control-Allow-Origin", "*");
			response.setHeader("Access-Control-Allow-Methods", "GET, POST");
			response.getWriter().println(jaRS);
			response.setStatus(HttpServletResponse.SC_OK);
			response.flushBuffer();

		}catch (Exception e){
			e.printStackTrace();
			//Assert.fail(e.getMessage());
		}

	}


	/**
	 * oss 回调
	 * @param request
	 * @param response
	 */
	@RequestMapping("/ossCallback")
	@ResponseBody
	public void ossCallback (HttpServletRequest request, HttpServletResponse response) throws IOException {

		//todo 此处需要 判断是否为oss请求
		Enumeration paramNames = request.getParameterNames();
		Map<String, String> respMap = new LinkedHashMap<String, String>();
		while (paramNames.hasMoreElements()){//遍历取出所有参数
			String name = paramNames.nextElement().toString();
			respMap.put(name, request.getParameter(name));
		}
		respMap.put("Status" ,"OK");

		//返回状态给OSS
		response.getWriter().println(JSONObject.fromObject(respMap).toString());
		response.setStatus(HttpServletResponse.SC_OK);
		response.flushBuffer();

	}

}
